package com.jike.price;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.getLatest12Month(new Date()));
    }

    public void days(){
        Test test = new Test();
        Date beforeDate = test.getBeforeDate(31);
        String beforeStr = new SimpleDateFormat("yyyy-MM-dd").format(beforeDate);
        String endStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        List<String> list = test.getDates(beforeStr, endStr);
        for (String s : list) {
            System.out.println(s);
        }
    }

    public String getLatest12Month(Date date){
        for(int i=0;i<=11;i++){
            Calendar  endFrom  =  Calendar.getInstance();
            endFrom.setTime(date);
            endFrom.add(Calendar.MONTH, i*-1);//11个月前
            String start = endFrom.get(Calendar.YEAR)+"-"+fillZero(endFrom.get(Calendar.MONTH)+1);
            System.out.println(start);
        }
        return "xxx";
    }
    /**
     * 格式化月份
     */
    public static String fillZero(int i){
        String month = "";
        if(i<10){
            month = "0" + i;
        }else{
            month = String.valueOf(i);
        }
        return month;
    }

    private Date getBeforeDate(int i) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DATE, i * -1);
        String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now.getTime());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date date = null;
        try {
            date = formatter.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public List<String> getDates(String cntDateBeg, String cntDateEnd) {
        List<String> list = new ArrayList<>();
        //拆分成数组
        String[] dateBegs = cntDateBeg.split("-");
        String[] dateEnds = cntDateEnd.split("-");
        //开始时间转换成时间戳
        Calendar start = Calendar.getInstance();
        start.set(Integer.valueOf(dateBegs[0]), Integer.valueOf(dateBegs[1]) - 1, Integer.valueOf(dateBegs[2]));
        Long startTIme = start.getTimeInMillis();
        //结束时间转换成时间戳
        Calendar end = Calendar.getInstance();
        end.set(Integer.valueOf(dateEnds[0]), Integer.valueOf(dateEnds[1]) - 1, Integer.valueOf(dateEnds[2]));
        Long endTime = end.getTimeInMillis();
        //定义一个一天的时间戳时长
        Long oneDay = 1000 * 60 * 60 * 24l;
        Long time = startTIme;
        //循环得出
        while (time <= endTime) {
            String date = new SimpleDateFormat("yyyyMMdd").format(new Date(time));
            list.add(date);
            time += oneDay;
        }
        return list;
    }
}
